package com.lagou.rpc.provider;

import com.lagou.rpc.ZkStrSerializer;
import com.lagou.rpc.provider.server.RpcServer;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@Slf4j
@SpringBootApplication
public class ServerBootstrapApplication implements CommandLineRunner {


    @Autowired
    RpcServer rpcServer;

    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrapApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                rpcServer.startServer("127.0.0.1", 8900);
            }
        }).start();
    }

    @Bean
    public ZkClient zkClient(){
        log.info("初始化zkClient连接");

        // 初始化zkClient
        ZkClient zkClient = new ZkClient("172.16.228.121:2181,172.16.228.122:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());

        // 读取java-zk节点的数据
        if (!zkClient.exists("/java-zk")) {
            log.error("zk上没有相关配置节点， 无法启动服务器");
            throw new RuntimeException("zk上没有相关配置节点， 无法启动服务器");
        }
       log.info("成功启动zk");

        return zkClient;
    }


}
